package com.steakliu.jsoup.cnblogs;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 功能说明：
 * <p>
 * Original @Author: steakliu-刘牌, 2022-09-01  19:31
 * <p>
 * Copyright (C)2020-2022  steakliu All rights reserved.
 */
@RestController
public class Cnblogs {

    @lombok.SneakyThrows
    @GetMapping("/get")
    public List<Map<String, String>> reptile() throws IOException, IOException {
        String url = "https://www.cnblogs.com";
        List<Map<String, String>> mapList = new ArrayList<>();

        Document document = Jsoup.connect(url).get();
        Elements elements = document.select("div#main_flow > .card > #post_list > .post-item");
        for (Element element : elements) {
            Map<String,String> map = new HashMap<>(8);
            String title = element.select("div.post-item-text > .post-item-title").text();
            map.put("title",title);
            String detailUrl = element.select("div.post-item-text > a[href]").attr("href");;
            map.put("detailUrl",detailUrl);
            String introduction = element.select("div.post-item-text > .post-item-summary").text();
            map.put("introduction",introduction);
            String author = element.select(".post-item-foot > .post-item-author").text();
            map.put("author",author);
            String time = element.select(".post-item-foot > .post-meta-item > span").first().text();
            map.put("time",time);
            getDetail(map);
            mapList.add(map);
        }
        return mapList;
    }

    public static void getDetail(Map<String,String> map) throws IOException {
        String detailUrl = map.get("detailUrl");
        Document document = Jsoup.connect(detailUrl).get();
        String detail = document.select(".postBody > #cnblogs_post_body").text();
        map.put("detail",detail);
    }
}
